package gang.org.springframework.boot.autoconfigure.web.servlet;

import gang.org.springframework.framework.util.GangObjectUtils;
import gang.org.springframework.framework.util.GangStringUtils;

import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @Author：gang.chen
 * @Date：2023/10/13 9:28
 */

public class GangServletRegistrationBean<T extends Servlet> extends GangDynamicRegistrationBean<ServletRegistration.Dynamic>{

    public T servlet;

    private int loadOnStartup = -1;
    public boolean alwaysMapUrl = true;

    public Set<String> urlMappings = new LinkedHashSet<>();


    public GangServletRegistrationBean(T servlet, boolean alwaysMapUrl, String... urlMappings) {
        this.servlet = servlet;
        this.alwaysMapUrl = alwaysMapUrl;
        this.urlMappings.addAll(Arrays.asList(urlMappings));
    }

    public GangServletRegistrationBean(T servlet, String... urlMappings){
        this(servlet, true, urlMappings);
    }

    public T getServlet() {
        return servlet;
    }

    @Override
    public String getDescription() {
        return "servlet " + getServletName();
    }

    public String getServletName(){
        return getOrDeduceName(this.servlet);
    }

    @Override
    public ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) {
        String name = getServletName();
        return servletContext.addServlet(name, this.servlet);
    }

    @Override
    public void configure(ServletRegistration.Dynamic registration) {
        super.configure(registration);

        String[] urlMapping = GangStringUtils.toStringArray(this.urlMappings);

        //if(urlMapping.length == 0 && this.alwaysMapUrl)

        if (!GangObjectUtils.isEmpty(urlMapping)) {
            registration.addMapping(urlMapping);
        }
        registration.setLoadOnStartup(this.loadOnStartup);

        //if(this.multipartConfig != null)
    }

    public void addUrlMapping(String... urlMappings){
        this.urlMappings.addAll(Arrays.asList(urlMappings));
    }
}
